﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Amgine
{
    partial class LinkmanEditForm : Form
    {
        private Linkman linkman;
        private List<LinkmanGroup> groupList;

        public LinkmanEditForm(Linkman linkman)
        {
            InitializeComponent();
            this.linkman = (linkman == null ? new Linkman() : linkman);
            groupList = DBHelper.listAllLinkmanGroup();
        }

        private void LinkmanEditForm_Load(object sender, EventArgs e)
        {
            int position = -1;
            int count = 0;
            foreach (LinkmanGroup group in groupList)
            {
                comboBox_group.Items.Add(group.Name);
                if (group.ID == linkman.GroupId)
                {
                    position = count;
                }
                count++;
            }
            comboBox_group.SelectedIndex = position;

            textBox_name.Text = linkman.Name;
            textBox_remark.Text = linkman.Remark;
        }

        private void button_confirm_Click(object sender, EventArgs e)
        {
            linkman.Name = textBox_name.Text;
            linkman.Remark = textBox_remark.Text;

            if (comboBox_group.SelectedIndex == -1)
            {
                MessageBox.Show("请选择所属分组", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            linkman.GroupId = groupList.ElementAt(comboBox_group.SelectedIndex).ID;

            if (validateData())
            {
                if (linkman.createOrUpdate())
                {
                    DialogResult = DialogResult.OK;
                }
                else
                {
                    DialogResult = DialogResult.Retry;
                }
                Close();
            }
        }

        private bool validateData()
        {
            if (string.IsNullOrWhiteSpace(linkman.Name))
            {
                MessageBox.Show("联系人姓名不可为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrWhiteSpace(linkman.Remark))
            {
                MessageBox.Show("备注不可为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }

        private void button_cancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
    }
}
